package com.yzg.fork;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @author misterWei
 * @create 2020年06月14号:20点49分
 * @mailbox forcontinue@163.com
 */
@Slf4j(topic = "c.ForkJoinMain")
public class ForkJoinMain {

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        forkJoinPool.invoke(new ForkTask(1,5));
    }

}

/**
 * 继承 RecursiveTask 说明是有返回值的
 * 继承 RecursiveAction  说明是没有返回值的
 *
 * 计算 start 与 end  之间的数进行累加
 */
@Slf4j(topic = "c.ForkTask")
class ForkTask extends RecursiveTask<Integer> {
    private int start;
    private int end;

    public ForkTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    public String toString() {
        return "ForkTask{" +
                "start=" + start +
                ", end=" + end +
                '}';
    }

    @Override
    protected Integer compute() {
        if (start == end) return start;
        if (end - start == 1) return start + end;
        int temp = (end + start) / 2;
        ForkTask t1 = new ForkTask(start, temp); // 1,3
        t1.fork();
        ForkTask t2 = new ForkTask(temp + 1, end); // 4,5
        t2.fork();
        log.debug("fork() {} + {} = ?", t1, t2);
        int result = t1.join() + t2.join();
        log.debug("join() {} + {} = {}", t1, t2, result);
        return result;

    }
}
